package keqiang.com.kq_flutter_core_widget.channel;

import android.content.Context;

import androidx.annotation.NonNull;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import me.zhouzhuo810.magpiex.utils.SpUtil;

/**
 * 获取本地存储的数据
 *
 * @author zhouzhuo810
 * @date 2023/3/13 17:49
 */
public class NativeKeyValueChannel extends MethodChannel {
    
    // 通道id
    private static final String CHANNEL = "flutter.keqiang.com/kv";
    
    private static final String METHOD_GET_BOOL = "getBool";
    private static final String METHOD_SET_BOOL = "setBool";
    private static final String METHOD_GET_STRING = "getString";
    private static final String METHOD_SET_STRING = "setString";
    private static final String METHOD_GET_INT = "getInt";
  
    private Context mContext;
    
    public NativeKeyValueChannel(@NonNull BinaryMessenger messenger) {
        super(messenger, CHANNEL);
        
        init();
    }
    
    public void setContext(Context context) {
        mContext = context;
    }
    
    private void init() {
        setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                switch (call.method) {
                    case METHOD_GET_BOOL:
                        String key = call.argument("key");
                        Boolean defValue = call.argument("defaultValue");
                        result.success(SpUtil.getBoolean(key, defValue != null && defValue));
                        break;
                    case METHOD_SET_BOOL:
                        key = call.argument("key");
                        Boolean value = call.argument("value");
                        SpUtil.putBoolean(key, value != null && value);
                        result.success(true);
                        break;
                    case METHOD_GET_STRING:
                        key = call.argument("key");
                        String defString = call.argument("defaultValue");
                        result.success(SpUtil.getString(key, defString));
                        break;
                    case METHOD_SET_STRING:
                        key = call.argument("key");
                        SpUtil.putString(key, call.argument("value"));
                        result.success(true);
                        break;
                    case METHOD_GET_INT:
                        key = call.argument("key");
                        Integer defInt = call.argument("defaultValue");
                        result.success(SpUtil.getInt(key, defInt == null ? 0 : defInt));
                        break;
                }
            }
        });
    }
}
